﻿using Blazored.LocalStorage;
using Microsoft.AspNetCore.Components.Authorization;
using System.Net.Http.Headers;

namespace VaccineClient.Services
{
    public class AuthService : IAuthService
    {
        private readonly HttpClient _httpClient;
        private readonly AuthenticationStateProvider _authenticationStateProvider;
        private readonly ILocalStorageService _localStorage;

        public AuthService(HttpClient httpClient,
                      AuthenticationStateProvider authenticationStateProvider,
                      ILocalStorageService localStorage)
        {
            _httpClient = httpClient;
            _authenticationStateProvider = authenticationStateProvider;
            _localStorage = localStorage;
        }

        public async Task<LoginResult> Login(string userName, string password)
        {
            var response = await _httpClient.PostAsync($"/api/v1/user/auth/{userName}/{password}", null);
            var data = await response.Content.ReadAsStringAsync();
            //模拟登录
            var loginResult = new LoginResult();
            loginResult.Success = response.StatusCode == System.Net.HttpStatusCode.OK;
            if (loginResult.Success)
            {
                loginResult.Token = data;
            }
            else
            {
                loginResult.Error = data;
            }
            await _localStorage.SetItemAsync("authToken", loginResult.Token);
            await _localStorage.SetItemAsync("userName", userName);
            ((CustomAuthStateProvider)_authenticationStateProvider).MarkUserAsAuthenticated();
            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", loginResult.Token);
            return loginResult;
        }

        public async Task Logout()
        {
            await _localStorage.RemoveItemAsync("authToken");
        }
    }

    public interface IAuthService
    {
        Task<LoginResult> Login(string userName, string password);
        Task Logout();

    }

    public class LoginResult
    {
        public bool Success { get; set; }
        public string? Error { get; set; }
        public string? Token { get; set; }
    }
}
